package com.ideaaedi.springcloud.jd.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import com.ideaaedi.springcloud.jd.commonds.entity.BaseCodeMsgEnum;
import com.ideaaedi.springcloud.jd.commonds.entity.PageInfo;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysGroupPO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysGroupAddReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysGroupListReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysGroupUpdateReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysGroupDetailRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysGroupListRespVO;
import com.ideaaedi.springcloud.jd.commonds.exception.BaseException;
import com.ideaaedi.springcloud.jd.commonspring.mybatisplus.ServiceImplExt;
import com.ideaaedi.springcloud.jd.commonspring.util.JdContextUtil;
import com.ideaaedi.springcloud.jd.commonspring.validator.ValidTenant;
import com.ideaaedi.springcloud.jd.user.mapper.SysGroupMapper;
import com.ideaaedi.springcloud.jd.user.service.SysGroupService;
import com.ideaaedi.springcloud.jd.user.support.UserCheckSupport;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统-分组 服务实现类
 * </p>
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.5.B
 */
@Service
public class SysGroupServiceImpl extends ServiceImplExt<SysGroupMapper, SysGroupPO> implements SysGroupService {
    
    @Resource
    private UserCheckSupport userCheckSupport;
    
    @Nullable
    @Override
    @ValidTenant
    @Transactional(rollbackFor = Exception.class)
    public SysGroupDetailRespVO add(SysGroupAddReqVO req, boolean queryDetail) {
        String tenant = req.getTenant();
        if (StringUtils.isBlank(tenant)) {
            tenant = JdContextUtil.currUserTenantNonNull();
        }
        long id = IdWorker.getId();
        SysGroupPO po = new SysGroupPO();
        BeanUtils.copyProperties(req, po, BaseConstant.TENANT);
        po.setId(id);
        if (StringUtils.isNotBlank(tenant)) {
            po.setTenant(tenant);
        }
        save(po);
        return queryDetail ? detail(id) : null;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysGroupDetailRespVO delete(Long id) {
        Objects.requireNonNull(id, "id cannot be null.");
        SysGroupDetailRespVO resp = detail(id);
        removeById(id);
        return resp;
    }
    
    @Nullable
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysGroupDetailRespVO update(SysGroupUpdateReqVO req) {
        Long id = req.getId();
        String tenant = req.getTenant();
        SysGroupPO dbPo = getById(id);
        if (dbPo == null) {
            throw new BaseException("group id -> " + id, BaseCodeMsgEnum.DATA_NON_EXIST_OR_NON_DATA_PERMISSION);
        }
        if (StringUtils.isBlank(tenant)) {
            tenant = dbPo.getTenant();
        }
        // 校验code是否被占用
        String code = req.getCode();
        if (code != null) {
            userCheckSupport.checkExistSameGroupCode(tenant, code, id);
        }
        
        // mybatis-plus默认的updateById方法，更新策略默认是NOT_NULL（即更新数据时数据为NULL值时将不更新进数据库）
        SysGroupPO po = new SysGroupPO();
        BeanUtils.copyProperties(req, po, BaseConstant.TENANT);
        po.setTenant(tenant);
        updateById(po);
        return detail(id);
    }
    
    @Nullable
    @Override
    public SysGroupDetailRespVO detail(Long id) {
        Objects.requireNonNull(id, "id cannot be null.");
        SysGroupPO po = getById(id);
        if (po == null) {
            return null;
        }
        SysGroupDetailRespVO resp = new SysGroupDetailRespVO();
        BeanUtils.copyProperties(po, resp);
        return resp;
    }
    
    @Override
    public PageInfo<SysGroupListRespVO> list(SysGroupListReqVO req) {
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        String tenant = req.getTenant();
        String type = req.getType();
        String name = req.getName();
        String code = req.getCode();
        Integer deptId = req.getDeptId();
        Integer state = req.getState();
        
        // 分页查
        IPage<SysGroupPO> pageInfo = new Page<>(pageNum, pageSize);
        IPage<SysGroupPO> page = this.baseMapper.selectPage(pageInfo,
                new LambdaQueryWrapper<SysGroupPO>()
                        .eq(tenant != null && tenant.trim().length() != 0, SysGroupPO::getTenant, tenant)
                        .eq(type != null && type.trim().length() != 0, SysGroupPO::getType, type)
                        .eq(name != null && name.trim().length() != 0, SysGroupPO::getName, name)
                        .eq(code != null && code.trim().length() != 0, SysGroupPO::getCode, code)
                        .eq(deptId != null, SysGroupPO::getDeptId, deptId)
                        .eq(state != null, SysGroupPO::getState, state)
                        .last("ORDER BY type ASC, IFNULL(sort, " + Integer.MAX_VALUE + ") ASC, id DESC")
        );
        // 转换为resp模型
        List<SysGroupPO> records = page.getRecords();
        List<SysGroupListRespVO> list;
        if (CollectionUtils.isEmpty(records)) {
            list = Collections.emptyList();
        } else {
            list = records.stream().map(po -> {
                SysGroupListRespVO resp = new SysGroupListRespVO();
                BeanUtils.copyProperties(po, resp);
                return resp;
            }).collect(Collectors.toList());
        }
        return PageInfo.of(page.getTotal(), pageNum, pageSize, list);
    }
}
